<?php
declare (strict_types=1);

namespace app\service;

use app\model\MatchParam;
use app\model\TLabel;
use app\model\TUserMatchParam;
use app\traits\ServiceTrait;
use app\util\JwtUtil;
use app\service\AuthGroupService;
use think\facade\Db;

/**
 * 用户匹配
 * Class TUserMatchParamService
 * @package app\service
 */
class TUserMatchParamService
{
    //仓库，带命名空间
    public static $repository = 'app\repository\TUserMatchParamRepository';

    use ServiceTrait;

    /**
     * @param $labelId
     * @return array
     */
    public static function selectSubCategoryId($labelId)
    {
        // 列表
        $table = TUserMatchParam::$_table;
        $r = Db::table($table)->where(['label_id' => $labelId])->order('sub_category_id', 'asc')->group('sub_category_id')->column('sub_category_id');
        if (empty($r)) {
            return $r;
        }

        return $r;
    }

    /**
     * 修改以及添加
     * @param $data
     */
    public static function addBatch($data)
    {
        $delData = [];
        $addData = [];
        $date = date('Y-m-d H:i:s');
        $table = TUserMatchParam::$_table;
        $table_match_param = MatchParam::$_table;
        foreach ($data as $v) {
            $delData['labelId'] = $v['labelId'];
            $delData['subCategoryId'] = $v['subCategoryId'];
            $group_id = Db::name($table_match_param)->where(['id' => $v['matchGroupId']])->column('group_id');

            $addData[] = [
                'label_id' => $v['labelId'],
                'sub_category_id' => $v['subCategoryId'],
                'match_group_id' => $group_id[0],
                'param_val' => $v['paramVal'],
                'create_time' => $date,
                'update_time' => $date,
            ];
        }
        $dellabelId = $delData['labelId'];
        $delsubCategoryId = $delData['subCategoryId'];

        Db::table($table)->where(['label_id' => $dellabelId, 'sub_category_id' => $delsubCategoryId])->delete();
        Db::table($table)->insertAll($addData);
    }

    /**
     * 根据labelId获取分类ID以及groupId
     * @param $labelIdArr
     */
    public static function getSubCidAndGroupIdByLabelId($labelIdArr)
    {
        // 列表
        $table = TUserMatchParam::$_table;
        $cidGroupIds = Db::table($table)->where([['label_id', 'in',  $labelIdArr]])->column('sub_category_id, match_group_id');
        if (empty($cidGroupIds)) {
            return [];
        }
        $goods = GoodsMatchParamService::getGoodsIdByCidAndGroupId($cidGroupIds);
        return $goods;
    }
}
